package crazyjava;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFutureTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ExecutorService threadPool1 = Executors.newSingleThreadExecutor();
		Future<String> ouput= threadPool1.submit(new Callable<String>() {

			public String call() throws Exception {
				
				return "test";
			}
		});
		try {
			System.out.println(ouput.get());
		} catch (InterruptedException e1) {
			
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			
			e1.printStackTrace();
		}
		threadPool1.shutdown();
		
		ExecutorService threadPool = Executors.newFixedThreadPool(4);
		CompletionService<String> completionService = new  ExecutorCompletionService<String>(threadPool);
		for(int i=1;i<10;i++){
			final int j=i;
			completionService.submit(new Callable<String>() {
				
				public String call() throws Exception {
					// TODO Auto-generated method stub
					int time = new Random().nextInt(5000);
					Thread.sleep(time);
					return "task "+j+" for " +time;
				}
			});
		}
		for(int i=1;i<10;i++){
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		threadPool.shutdown();

	}

}
